const { objForEach } = require("../../utils/util");

const App = getApp();
// 默认未登录的灰色头像
const defaultAvatarUrl = 'https://mmbiz.qpic.cn/mmbiz/icTdbqWNOwNRna42FI242Lcia07jQodd2FJGIYQfG0LAJGFxM4FbnQP6yfMxBgJ0F3YRqJCJ1aPAK2dQagdusBZg/0'
Page({
    data: {
      showPPP: 'no',
      qaid:0,
      senduid:0,
      buyid:0,  //当此参数大于0，说明该试卷有人赠送
      qaObj:{},
      fromShare:'no', //是否开源于分享打开
      imgBoxArr:[0,3],
      imgList:[], //商品图数据
      tipMsg:'',
      gotoAsk:"no",
      goIndexBtnFont:'回到首页',
      zimuArr:['A','B','C','D','E','F'],
      allQestionArr:[],
      
      inLine:'no',  //是否首次进入授权得到电话号码
      trueMobile: "",
      showBottomPopup:false,
      avatarUrl: defaultAvatarUrl,
      _saveFromShare: 'no',  //暂存是否转发链接的结果
      qaFromUid:0,  // 如果id大于0，视为此套试卷为赠送试卷
    },
    onLoad: function(options) {
      console.log('试卷详情传递过来的参数值：', options);
      //qaid，试卷id，订单id，赠送人id，fromShare会的试卷id，订单id，赠送人id同步出现
      this.setData({qaid:options.qaid, buyid:options.buyid, senduid:options.senduid, fromShare:options.fromShare,inLine:options.inLine,trueMobile:wx.getStorageSync('true_mobile')});
      if(this.data.fromShare=='yes'){
        this.setData({_saveFromShare:'yes', goIndexBtnFont:"点击答题挣积分"});
      }

      const pages = getCurrentPages();
      const currentPage = pages[pages.length - 1];
      const path = currentPage.route;
      const para = currentPage.options;
      var oldPath = '/'+path+'?'+App.getShareUrlParams(para);
      console.log('当前页面路径：', path, options, oldPath);
      var newPath = "/pages/studycenter/allqainfo?" + App.getShareUrlParams({qaid:this.data.qaid});
      //老地址是扫码或转发过来的地址，新地址是领取试卷后后人不能再领取的地址
      //避免朋友送的试卷，比方A送我的试卷，我转发给C，实际上还是A送给C。
      this.setData({oldPath:oldPath, newPath:newPath, sharePath:oldPath});
      //如果是进线引流，且没有得到手机号，先强制将领取试卷按钮隐藏，等获取手机号以后展示领取试卷按钮
      var trueMobile = this.data.trueMobile;
      if(this.data.inLine=='yes'){
        if(trueMobile=='' || trueMobile==null || trueMobile==undefined){
          this.setData({fromShare:"no"});
        }
      }
      
      this.getAllQa();
      // 加载页面数据
      this.getPageData();
      // 设置是否显示价格，如果不是显示价格，代表免费领取
      this.setShowPPP();
    },
    setShowPPP(){
      var _this = this;
      var wxAppObj = wx.getStorageSync('wxapp');
      App._get('user.index/detail222', {uid:wx.getStorageSync('user_id')}, function(result) {
        var getAllJifen = result.data.userObj.allsend_points;
        var bigJifen = wxAppObj.max_gift_jifen;
        var isShopPrice = getAllJifen >= bigJifen ? 'yes' : 'no';
        //isShopPrice = 'yes'; //测试
        _this.setData({showPPP:isShopPrice});
        console.log('问答详情页面中获取个人信息', result);
      });
    },
    onShow(){
      this.setData({user_id: wx.getStorageSync('user_id')});
    },
    getSendQaBox(){
      let _this = this;
      var qaid = this.data.qaid;
      var buyid = this.data.buyid>0 ? this.data.buyid : 0;
      var senduid = this.data.senduid>0 ? this.data.senduid : 0;
      var inLine = this.data.inLine>0 ? this.data.inLine: 0;
      //领取试卷，传递是否为采单进线，yes为采单进线的领取
      // 采单进线领取，需要扣除代理商的后台总账户中的余额。
      // buyid有可能为0，新进线的还未领取任何试题，试题刚刚入库，所以buyid此时为0
      App._get('askanswer/getSendQaByShare', {"showPPP":this.data.showPPP, buyid:buyid, senduid:senduid, myuid:wx.getStorageSync('user_id'), qaid:qaid, inLine:inLine}, result => {
        var dd = result.data.back;
        if(dd.state=='sendOk'){
          //App.showSuccess('已自动为您领取好友赠送的试卷');
          //如果不是进线引流，正常领取了朋友转发的试卷后，则再次分享的地址变为新的地址
          var _newbuyid = dd.newBuyid>0 ? dd.newBuyid : _this.data.buyid;
          var _sharePath = dd.newBuyid>0 ? _this.data.oldPath : _this.data.newPath;
          _this.setData({tipMsg:dd.msg, gotoAsk:'yes', buyid:_newbuyid, sharePath:_sharePath});
        }
        else{
          _this.setData({tipMsg:dd.msg});
        }
        App.showError(dd.msg,function(){
          _this.gotoIndexFun();
        });
      });
    },
    /** 根据checkIds获取试卷列表 */
    getAllQa(){
      let _this = this;
      App._get('askanswer/getAllQestion', {qaid:this.data.qaid}, result => {
        _this.setData({allQestionArr:result.data.list, qaObj:result.data.qaObj});
        console.log(result);
      });
    },
    getPageData(){
      let _this = this;
      var bigObj = {
        type: "banner",
        data:[],
        name: "图片轮播",
        style: {btnColor: "#ffffff", btnShape: "round"},
        params: {interval: "2800"},
      };
      App._get('askanswer/getRandGoodImg', {page_id:0}, result => {
        var list = result.data.list;
        for (let i in list) {
          bigObj.data.push({imgUrl:list[i]['file_img_allpath'], linkUrl:""});
        }
        _this.setData({items:[bigObj], imgList:list});	//只要首页banner
      });
    },
    /** 暂时取消转发分享，问答详情页面转发作为正常转发 */
    onShareAppMessage() {
      const _this = this;
      return {
        title: "答题挣积分，积分换礼品",
        imageUrl:_this.data.imgList[0]['file_img_allpath'],
        path:_this.data.newPath
        //path: _this.data.sharePath
      };
    },
    onShareTimeline() {
      const _this = this;
      return {
        title: "答题挣积分，积分换礼品",
        imageUrl:_this.data.imgList[0]['file_img_allpath'],
        path:_this.data.newPath
        //path: _this.data.sharePath
      };
    },
    gotoIndex(){
      this.getSendQaBox();
    },
    gotoIndexFun(){
      if(this.data.gotoAsk=='yes'){
        var buyid = this.data.buyid;
        console.log('领取成功后，跳转到到答题-------------------- buyid:'+buyid);
        //如果此人领取了问答题，点击按钮直接开始答题，fromShare此参数可以让用户答完题直接跳转到用户中心页面
        wx.redirectTo({
          url: '/pages/studycenter/beganswer?fromShare=yes&buyid=' + buyid,
        });
      }
      else{
        wx.reLaunch({
          url: '/pages/index/index',
        });
      }
    },
    //打开手机登录弹出层
    openPopupLoginDiv(){
      this.setData({showBottomPopup:true})
    },
    // 点击获取手机号
    getUserMobile(e){
      let _this = this
      console.log("获取用户手机号", e)
      if(e.detail.iv && 1){
        App._post_form('user/getwxMobile', {
          user_id: wx.getStorageSync('user_id'),
          encryptedData: e.detail.encryptedData,
          code: e.detail.code,
          iv: e.detail.iv,
        }, function(result) {
          console.log("获取到微信手机号码------", result)
          let nowMobile = result.data.true_mobile
          if(nowMobile!=''){
            wx.setStorageSync('true_mobile', result.data.true_mobile);
            _this.setData({trueMobile:result.data.true_mobile,showBottomPopup:false,
              user_id: wx.getStorageSync('user_id')})
            //如果得到了手机号，并且上次暂存的分享来源是yes，则展示领取试题的按钮
            if(_this.data._saveFromShare=='yes'){
              _this.setData({fromShare:'yes'})
              //获取电话号码之后，自动领取该试卷，进入答题状态
              _this.gotoIndex();
            }
          }
        }, false, function() {
          wx.hideLoading();
          _this.onClosePopup();
        })
      }
    },
    //关闭顶层弹出层
    onClosePopup(){
      this.setData({showBottomPopup:false})
    },
});